package com.dsit.sq.mydefineview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
import android.widget.ImageView;

import com.dsit.sq.R;

/**
 * Created by dsit_dev04 on 2016/10/11.
 */
public class PanView extends ImageView {
    private SurfaceHolder mHolder;
    /**
     * 与SurfaceHolder绑定的Canvas
     */
    private Canvas mCanvas;
    /**
     * 用于绘制的线程
     */
    private Thread t;
    /**
     * 线程的控制开关
     */
    private boolean isRunning;

    /**
     * 抽奖的文字
     */
    private String[] mStrs = new String[]{"单反相机", "IPAD", "恭喜发财", "IPHONE",
            "妹子一只", "恭喜发财", "妹子一只", "恭喜发财"};
    /**
     * 每个盘块的颜色
     */
    private int[] mColors = new int[]{0xFFFFC300, 0xFFF17E01, 0xFFFFC300,
            0xFFF17E01, 0xFFFFC300, 0xFFF17E01, 0xFFFFC300, 0xFFF17E01};
    private int[] mColors1 = new int[]{0xFF1f2538, 0xFF1b1d2f};
    /**
     * 与文字对应的图片
     */
    private int[] mOnImgs = new int[]{R.mipmap.icon_gaoya_on, R.mipmap.icon_jueyuan_on,
            R.mipmap.icon_gaowen_on, R.mipmap.icon_dianci_on, R.mipmap.icon_qingxie_on,
            R.mipmap.icon_chongdian_on, R.mipmap.icon_guzhang_on, R.mipmap.icon_dongli_on};
    private int[] mOffImgs = new int[]{R.mipmap.icon_gaoya_off, R.mipmap.icon_jueyuan_off,
            R.mipmap.icon_gaowen_off, R.mipmap.icon_dianci_off, R.mipmap.icon_qingxie_off,
            R.mipmap.icon_chongdian_off, R.mipmap.icon_guzhang_off, R.mipmap.icon_dongli_off};
    private Bitmap centerBitmap;

    /**
     * 盘块的个数
     */
    private int mItemCount = 8;

    /**
     * 绘制盘块的范围
     */
    private RectF mRange = new RectF();
    /**
     * 圆的直径
     */
    private int mRadius;
    /**
     * 绘制盘快的画笔
     */
    private Paint mArcPaint;

    private Paint blackClorPaint;

    /**
     * 绘制文字的画笔
     */
    private Paint mTextPaint;

    /**
     * 滚动的速度
     */
    private double mSpeed;
    private volatile float mStartAngle = 0;
    /**
     * 是否点击了停止
     */
    private boolean isShouldEnd;

    /**
     * 控件的中心位置
     */
    private int mCenter;
    /**
     * 控件的padding，这里我们认为4个padding的值一致，以paddingleft为标准
     */
    private int mPadding;

    /**
     * 背景图的bitmap
     */
//    private Bitmap mBgBitmap = BitmapFactory.decodeResource(getResources(),
//            R.mipmap.bg_beijing);
    /**
     * 文字的大小
     */
    private float mTextSize = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());

    public PanView(Context context) {
        this(context, null);
    }

    public PanView(Context context, AttributeSet attrs) {
        super(context, attrs);

//        mHolder = getHolder();
//        mHolder.addCallback(this);

        // setZOrderOnTop(true);// 设置画布 背景透明
        // mHolder.setFormat(PixelFormat.TRANSLUCENT);

        setFocusable(true);
        setFocusableInTouchMode(true);
        this.setKeepScreenOn(true);
        init();
    }

    private void init() {
        blackClorPaint = new Paint();
        blackClorPaint.setAntiAlias(true);
        blackClorPaint.setDither(true);
        blackClorPaint.setColor(0xFF000000);
        // 初始化绘制圆弧的画笔
        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(true);
        mArcPaint.setDither(true);
        // 初始化绘制文字的画笔
        mTextPaint = new Paint();
        mTextPaint.setColor(0xFFffffff);
        mTextPaint.setTextSize(mTextSize);

        // 初始化图片
//        centerBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg_xiafang_light_on);
//        mImgsBitmap = new Bitmap[mItemCount];
//        for (int i = 0; i < mItemCount; i++) {
//            mImgsBitmap[i] = BitmapFactory.decodeResource(getResources(),
//                    mOnImgs[i]);
//        }

        // 开启线程
//        isRunning = true;
//        t = new Thread(this);
//        t.start();
    }

    /**
     * 设置控件为正方形
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = Math.min(getMeasuredWidth(), getMeasuredHeight());
        // 获取圆形的直径
        mRadius = width - getPaddingLeft() - getPaddingRight();
        // padding值
        mPadding = getPaddingLeft();
        // 中心点
        mCenter = width / 2;
        setMeasuredDimension(width, width);
    }

//    @Override
//    public void surfaceCreated(SurfaceHolder holder) {
//        blackClorPaint = new Paint();
//        blackClorPaint.setAntiAlias(true);
//        blackClorPaint.setDither(true);
//        blackClorPaint.setColor(0xFF000000);
//        // 初始化绘制圆弧的画笔
//        mArcPaint = new Paint();
//        mArcPaint.setAntiAlias(true);
//        mArcPaint.setDither(true);
//        // 初始化绘制文字的画笔
//        mTextPaint = new Paint();
//        mTextPaint.setColor(0xFFffffff);
//        mTextPaint.setTextSize(mTextSize);
//        // 圆弧的绘制范围
//        mRange = new RectF(getPaddingLeft(), getPaddingLeft(), mRadius
//                + getPaddingLeft(), mRadius + getPaddingLeft());
//
//        // 初始化图片
//        mImgsBitmap = new Bitmap[mItemCount];
//        for (int i = 0; i < mItemCount; i++) {
//            mImgsBitmap[i] = BitmapFactory.decodeResource(getResources(),
//                    mImgs[i]);
//        }
//
//        // 开启线程
////        isRunning = true;
////        t = new Thread(this);
////        t.start();
//    }

//    @Override
//    public void surfaceChanged(SurfaceHolder holder, int format, int width,
//                               int height) {
//        // TODO Auto-generated method stub
//
//    }
//
//    @Override
//    public void surfaceDestroyed(SurfaceHolder holder) {
//        // 通知关闭线程
//        isRunning = false;
//    }

//    @Override
//    public void run() {
//        // 不断的进行draw
//        while (isRunning) {
//            long start = System.currentTimeMillis();
//
//            long end = System.currentTimeMillis();
//            try {
//                if (end - start < 50) {
//                    Thread.sleep(50 - (end - start));
//                }
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//
//        }
//
//    }

    //圆环颜色
    private static int[] doughnutColors = new int[]{0xFF2666a2, 0xFF24598a};
    private static int[] doughnutColors1 = new int[]{0xFF1f2538, 0xFF1b1d2f};

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 圆弧的绘制范围
        mRange = new RectF(getPaddingLeft(), getPaddingLeft(), mRadius
                + getPaddingLeft(), mRadius + getPaddingLeft());
        try {
            // 获得canvas
            mCanvas = canvas;
            if (mCanvas != null) {
                drawEach();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean centerIsOn = false;
    public int i = 0;
    public boolean isOnOne = false;
    public boolean isOnTwo = false;
    public boolean isOnThree = false;
    public boolean isOnFour = false;
    public boolean isOnFive = false;
    public boolean isOnSix = false;
    public boolean isOnSeven = false;
    public boolean isOnEight = false;
    public int time = 0;

    public void drawEach() {
        for (int i = 0; i < mItemCount; i++) {
            float sweepAngle = (float) (360 / mItemCount);
            mStartAngle = i * sweepAngle;
            float angle = (float) ((22.5 + mStartAngle) * (Math.PI / 180));
            int x = (int) (mCenter + mRadius / 4 * Math.cos(angle));
            int y = (int) (mCenter + mRadius / 4 * Math.sin(angle));
            RadialGradient gradient;
            Boolean isOn = false;
            switch (i) {
                case 0:
                    isOn = isOnOne;
                    break;
                case 1:
                    isOn = isOnTwo;
                    break;
                case 2:
                    isOn = isOnThree;
                    break;
                case 3:
                    isOn = isOnFour;
                    break;
                case 4:
                    isOn = isOnFive;
                    break;
                case 5:
                    isOn = isOnSix;
                    break;
                case 6:
                    isOn = isOnSeven;
                    break;
                case 7:
                    isOn = isOnEight;
                    break;
            }
            int[] colors = isOn ? doughnutColors : doughnutColors1;
            gradient = new RadialGradient(x, y, mRadius / 4, colors, null, Shader.TileMode.CLAMP);
            mArcPaint.setShader(gradient);
            //绘制扇形背景
            mCanvas.drawArc(mRange, mStartAngle, sweepAngle - 1, true,
                    mArcPaint);
            mCanvas.drawArc(mRange, mStartAngle + 44, 1, true, blackClorPaint);
            //绘制图片
            drawIcon(mStartAngle, i, isOn);
        }
    }

    public void startThread(){
        new Thread(moveThread).start();
    }

//    /*
//    * 根据当前旋转的mStartAngle计算当前滚动到的区域 绘制背景，不重要，完全为了美观
//    */
//    private void drawBg() {
//        mCanvas.drawColor(0xFFFFFFFF);
//        mCanvas.drawBitmap(mBgBitmap, null, new Rect(mPadding / 2,
//                mPadding / 2, getMeasuredWidth() - mPadding / 2,
//                getMeasuredWidth() - mPadding / 2), null);
//    }

//    /**
//     * @param startAngle
//     * @param sweepAngle
//     * @param string
//     */
//    private void drawText(float startAngle, float sweepAngle, String string)
//    {
//        Path path = new Path();
//        path.addArc(mRange, startAngle, sweepAngle);
//        float textWidth = mTextPaint.measureText(string);
//        // 利用水平偏移让文字居中
//        float hOffset = (float) (mRadius * Math.PI / mItemCount / 2 - textWidth / 2);// 水平偏移
//        float vOffset = mRadius / 2 / 6;// 垂直偏移
//        mCanvas.drawTextOnPath(string, path, hOffset, vOffset, mTextPaint);
//    }

    /**
     * 绘制图片
     *
     * @param startAngle
     */
    private void drawIcon(float startAngle, int i, boolean isOn) {
        // 设置图片的宽度为直径的1/8
        int imgWidth = mRadius / 6;

        float angle = (float) ((22.5 + startAngle) * (Math.PI / 180));

        int x = (int) (mCenter + mRadius * 19 / 48 * Math.cos(angle));
        int y = (int) (mCenter + mRadius * 19 / 48 * Math.sin(angle));
        // 确定绘制图片的位置
        Rect rect = new Rect(x - imgWidth / 2, y - imgWidth / 2, x + imgWidth
                / 2, y + imgWidth / 2);
        int imageId = isOn ? mOnImgs[i] : mOffImgs[i];
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageId);
//        centerIsOn = isOnOne | isOnTwo | isOnThree | isOnFive | isOnFour | isOnSix | isOnSeven | isOnEight;
        int centerId = R.mipmap.btn_shuju;
        centerBitmap = BitmapFactory.decodeResource(getResources(), centerId);
        mCanvas.drawBitmap(bitmap, null, rect, null);
        Rect rect1 = new Rect(mRadius / 4 - 10, mRadius / 4 - 10, mRadius * 3 / 4 + 10, mRadius * 3 / 4 + 10);
        mCanvas.drawBitmap(centerBitmap, null, rect1, null);
    }

    private final Runnable moveThread = new Runnable() {

        @Override
        public void run() {
            while (time != 0) {
                try {
                    isOnFive = !isOnFive;
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                postInvalidate();
            }
        }
    };
//    /**
//     * 点击开始旋转
//     *
//     * @param luckyIndex
//     */
//    public void luckyStart(int luckyIndex)
//    {
//        // 每项角度大小
//        float angle = (float) (360 / mItemCount);
//        // 中奖角度范围（因为指针向上，所以水平第一项旋转到指针指向，需要旋转210-270；）
//        float from = 270 - (luckyIndex + 1) * angle;
//        float to = from + angle;
//        // 停下来时旋转的距离
//        float targetFrom = 4 * 360 + from;
//        /**
//         * <pre>
//         *  (v1 + 0) * (v1+1) / 2 = target ;
//         *  v1*v1 + v1 - 2target = 0 ;
//         *  v1=-1+(1*1 + 8 *1 * target)/2;
//         * </pre>
//         */
//        float v1 = (float) (Math.sqrt(1 * 1 + 8 * 1 * targetFrom) - 1) / 2;
//        float targetTo = 4 * 360 + to;
//        float v2 = (float) (Math.sqrt(1 * 1 + 8 * 1 * targetTo) - 1) / 2;
//
//        mSpeed = (float) (v1 + Math.random() * (v2 - v1));
//        isShouldEnd = false;
//    }
//
//    public void luckyEnd()
//    {
//        mStartAngle = 0;
//        isShouldEnd = true;
//    }
}
